/**   
 * 文件名：updateUtil.java   
 *   
 * 版本信息：   
 * 日期：2011-12-19   
 * Copyright @ 2011 福富软件 版权所有  
 *       
 */
package com.m7788.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.m7788.screen.R;
import com.tool.custom.progressbar.CProgressBar;

/**   
 *    
 * 类名称：updateUtil   
 * 类描述： 下载更新  
 * 创建人： huanghsh   
 * 创建时间：2011-12-19 下午02:35:48   
 * 修改人：huanghsh   
 * 修改时间：2011-12-19 下午02:35:48   
 * 修改备注：   
 * @version    
 *    
 */
public class UpdateUtil {
	int notification_id=19172439;
    NotificationManager nm;
    Notification notification;
    
	private Context mContext;  
	private CProgressBar mProgress;
	private Dialog downloadDialog;
	private Activity activity;
	private Dialog mDialog;
	/**
	 * 下载后保存的应用名称
	 */
	private static final String FILENAME = "7788Assis.apk";
	private Handler handler = new Handler();  
	private String versionInfo,installUrl,key;
	
	private static final int DOWN_UPDATE = 1;
    
    private static final int DOWN_OVER = 2;
    
    private int progress;
    
    private Thread downLoadThread;
    
    private boolean interceptFlag = false;
    
    
    
    private Handler mHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case DOWN_UPDATE:
				if(progress>0){
					String text = progress+"%";
					mProgress.setProgress(progress,text);
				}
				break;
			case DOWN_OVER:
				downloadDialog.dismiss();
				update();//注意是小写的与Update()区别
				break;
			default:
				break;
			}
    	};
    };

	public UpdateUtil(Activity activity,Context context,String  versionInfo,String installUrl){
		this.mContext = context;
		this.versionInfo = versionInfo;
		this.installUrl = installUrl;
		this.key = key;
		this.activity=activity;
		
	}
	
    public synchronized void Update() {
		Log.d("Chenguangxi","dialog show");
		if(isValidContext(mContext)){
			if(mDialog!=null&&mDialog.isShowing()){
				mDialog.dismiss();
			}
			mDialog = new Builder(mContext)
					.setTitle("更新")
					.setMessage(versionInfo)// 设置内容
					.setPositiveButton("确定",// 设置确定按钮
							new OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
													int which) {
									dialog.dismiss();
//                            	notification();
									showDownloadDialog();
								}

							}).setNegativeButton("取消",
							new OnClickListener() {
								public void onClick(DialogInterface dialog,
													int whichButton) {
									dialog.dismiss();
								}
							}).create();

			mDialog.show();
		}
    }

	private boolean isValidContext (Context c){
		Activity a = (Activity)c;
		if (a.isDestroyed() || a.isFinishing()){
			Log.i("YXH", "Activity is invalid." + " isDestoryed-->" + a.isDestroyed() + " isFinishing-->" + a.isFinishing());
			return false;
		}else{
			return true;
		}
	}


	private void showDownloadDialog(){
		Builder builder = new Builder(mContext);
		builder.setTitle("软件版本更新");
		
		/*
		 * Android中通过布局文件来描述软件的界面，而通常在Activity中都是使用setContentView()来将布局显示出来。
		 * 但是如果我们在非Activity的情况下，而且需要对布局中的控件进行设置等操作，该如何处理呢?
		 * 这就需要使用到动态加载布局 LayoutInflater。
		 * 
		 * 它的作用类似于 findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件，并且实例化！
		 * 而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。
		 */
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.common_progress, null);
		mProgress = (CProgressBar)v.findViewById(R.id.progress);
		
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();
		
		downloadApk();
	}

    private void downloadApk(){
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
    }
    
    
    private Runnable mdownApkRunnable = new Runnable() {	
		@Override
		public void run() {
			try {
				HttpClient client = new DefaultHttpClient();   
                HttpGet get = new HttpGet(installUrl);   
                HttpResponse response;  
                response = client.execute(get);   
                HttpEntity entity = response.getEntity();   
                long length = entity.getContentLength();   
                InputStream is = entity.getContent();   
                FileOutputStream fileOutputStream = null;   
                if (is != null) {   
                	
                    File file = new File(Environment   
                            .getExternalStorageDirectory(), FILENAME);   
                    fileOutputStream = new FileOutputStream(file);   
                       
                    byte[] buf = new byte[1024];  
                    int count = 0;
                    do{   		   		
    		    		int numread = is.read(buf);
    		    		count += numread;
    		    	    progress =(int)(((float)count / length) * 100);
    		    	    //更新进度
    		    	    mHandler.sendEmptyMessage(DOWN_UPDATE);
    		    		if(numread <= 0){	
    		    			//下载完成通知安装
    		    			mHandler.sendEmptyMessage(DOWN_OVER);
    		    			break;
    		    		}
    		    		fileOutputStream.write(buf,0,numread);
    		    	}while(!interceptFlag);//点击取消就停止下载.

                }   
                fileOutputStream.flush();   
                if (fileOutputStream != null) {   
                    fileOutputStream.close();   
                }   
               // down(); 
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch(IOException e){
				e.printStackTrace();
			}
			
		}
	};  
   
    void update() {   
    	File apkfile =null;
    	
    	if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
    		apkfile = new File(
                        Environment.getExternalStorageDirectory(),
                        FILENAME);
    	else
    		apkfile = mContext.getCacheDir();
    	
        if (!apkfile.exists()) {
            return;
        }
        //自己程序读取apk文件并安装
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkfile),   
                "application/vnd.android.package-archive");   
        mContext.startActivity(intent);   
    }      
	
    
    
}
